<!--
 * @Author: 肖芬芳 10547202+xiao-fenfang@user.noreply.gitee.com
 * @Date: 2022-07-19 09:24:52
 * @LastEditors: 肖芬芳 1911683843@qq.com
 * @LastEditTime: 2022-12-13 16:34:03
 * @FilePath: \vue-api-serverc:\Users\Administrator\Desktop\vite-project\src\views\system\user\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <formSearch
    :form-item="formItem"
    :form-data="formData"
    :addBtn="true"
    :resetBtn="true"
    @clearForm="clearForm"
    @searchForm="searchForm"
    @addData="showDialog('新增')"
  >
    <template #selector>
      <el-select v-model="formData.role" clearable placeholder="请选择">
        <el-option
          v-for="(option, i) in roles"
          :label="option.label"
          :value="option.value"
          :key="i"
        />
      </el-select>
    </template>
  </formSearch>

  <tableList
    :table-title="tableTitle"
    :table-data="tableData"
    :pageInfo="pageInfo"
    @changeStatus="changeStatus"
    @handleSizeChange="handleSizeChange"
    @handleCurrentChange="handleCurrentChange"
    @prevClick="prevClick"
    @nextClick="nextClick"
  >
    <template #role="scope">
      <div>
        <!-- {{
          scope.slotval.role !== "undefined"
            ? role[scope.slotval.role].label
            : ""
        }} -->
        {{ scope.slotval.role }}
      </div>
    </template>
    <template #btn="scope">
      <el-button type="text" @click="handleEdit(scope.slotval._id)"
        >编辑</el-button
      >
      <el-button type="text" @click="handleResetPsw(scope.slotval._id)"
        >重置密码</el-button
      >
    </template>
  </tableList>
  <!-- <List/> -->

  <!-- 用户信息对话框 -->
  <AddDialog
    :add-Dialog="dialogOptions.dialogVisible"
    :title="dialogOptions.dialogTitle"
    :form-data="detailData"
    :roles="roles"
    @clost-btn="closeBtn"
    @save-btn="saveBtn"
  />
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import AddDialog from "./components/AddDialog.vue";
import init from "./option";
import UserServiceApi from "./api/userServieApi";
import { propsToAttrMap } from "@vue/shared";

const userServiceApi = new UserServiceApi();

// 搜索组件
const formItem = init.formItem;
const formData = reactive<any>({});

// 表格
const tableTitle = init.tableTitle;
const tableData = ref();
const pageInfo = reactive({
  currentPage: 1,
  pageSize: 10,
  totalCount: 100,
});

// 详情
const detailData = reactive<any>({});
const roles = ref<any>([]);

// 组件传递参数
const dialogOptions = reactive({
  dialogVisible: false,
  dialogTitle: "",
});

onMounted(() => {
  getSelector();
  getData();
});

// 获取列表数据
const getData = async () => {
  // 封装请求参数
  let params: any = {
    ...formData,
    pageSize: pageInfo.pageSize,
    currentPage: pageInfo.currentPage,
  };

  let data:any = await userServiceApi.getUserList(params);
  let totalCount: number = data.totalCount;
  let tabledata: Array<Object> = data.data;
  tabledata.forEach((item:any) => {
    item.createTime = formatTime("YYYY年mm月dd日 HH:MM:SS", item.createTime);
  });
  tableData.value = tabledata;
  // console.log(tableData.value);
  pageInfo.totalCount = totalCount;
  clearDetail();
};

// 将时间戳转换成时间格式
const formatTime = (format = "", num:any = new Date().getTime()) => {
  format = format || "YYYY-mm-dd HH:MM:SS"; //第一个参数不填时，使用默认格式
  let ret, date, renum;
  // 处理时间戳，js一般获取的时间戳是13位，PHP一般是10位,根据实际情况做判断处理
  if (num.toString().length == 10) {
    date = new Date(parseInt(num) * 1000);
  } else {
    date = new Date(parseInt(num));
  }
  const opt:any = {
    Y: date.getFullYear().toString(), // 年
    m: (date.getMonth() + 1).toString(), // 月
    d: date.getDate().toString(), // 日
    H: date.getHours().toString(), // 时
    M: date.getMinutes().toString(), // 分
    S: date.getSeconds().toString(), // 秒
    // 目前用的是这六种符号,有其他格式化字符需求可以继续添加，值必须转化成字符串
  };
  for (var k in opt) {
    ret = new RegExp("(" + k + "+)").exec(format);
    if (ret) {
      renum = ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"); //根据复数前面是否补零,如“mm”补零，单“m”前面不补零
      format = format.replace(ret[1], renum); //替换
    }
  }
  return format;
};

const searchForm = () => {
  // console.log(formData);
  // console.log(pageInfo);
  getData();
};

const changeStatus = async (userId: string) => {
  let res = await userServiceApi.changeStatus({ id: userId });
  getData();
};

// 获取详情信息
const getDetail = async (id: string) => {
  console.log(id);
  let res = await userServiceApi.detail(id);
  let data:any=res.data
  // 利用delete删除属性
  delete data.createTime
  delete data.status
  // let {createTime,status,...data}=res.data  //利用重构删除属性
  return data;
};

// 获取选择器的信息
const getSelector = async () => {
  roles.value = []; //清空数组
  let {data}:any= await userServiceApi.roleSelector();
  data.forEach((item:any) => {
    if (item.status == 1) {
      roles.value.push({ role: item.role, value: item.role });
    }
  });
};

// 点击新增/编辑弹窗
const showDialog = async (title: string) => {
  if(title=='新增'){
    clearDetail()
  }
  getSelector();
  dialogOptions.dialogVisible = true;
  dialogOptions.dialogTitle = title;
};

// 编辑用户
const handleEdit = async (id: string) => {
  let detail = await getDetail(id);
  Object.keys(detail).forEach((key) => {
    detailData[key]=detail[key]
  });
  showDialog("编辑");
};

const closeBtn = () => {
  clearDetail();
  dialogOptions.dialogVisible = false;
};

const saveBtn = () => {
  clearForm();
  clearDetail();
  dialogOptions.dialogVisible = false;
};

const clearForm = () => {
  // 清空搜索表单
  pageInfo.currentPage = 1;
  getData();
};

const clearDetail = () => {
  // console.log("执行了clearDetail")
  // 清空详情信息
  Object.keys(detailData).map((key) => {
    detailData[key] = "";
  });
  console.log(detailData)
};

const handleSizeChange = (pageSize: number) => {
  pageInfo.pageSize = pageSize;
  getData();
};

const handleCurrentChange = (currentPage: number) => {
  pageInfo.currentPage = currentPage;
  getData();
};

const prevClick = (currentPage: number) => {
  pageInfo.currentPage = currentPage;
  getData();
};

const nextClick = (currentPage: number) => {
  pageInfo.currentPage = currentPage;
  getData();
};

const handleResetPsw = (id) => {
  alert("重置密码");
};
</script>

<style lang="scss">
</style>
